package com.example.springbootdemo.util;

import com.example.springbootdemo.bean.FastDfsProperties;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * FastDFS文件上传
 * @author hh
 * @date 2022/3/3
 */
@Component
public class FastDfsUtils {

    private final Logger log = LoggerFactory.getLogger(FastDfsUtils.class);

    private final FastFileStorageClient fastFileStorageClient;

    private final FastDfsProperties fastDfsProperties;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif","image/jpg","image/png");

    public FastDfsUtils(FastFileStorageClient fastFileStorageClient, FastDfsProperties fastDfsProperties) {
        this.fastFileStorageClient = fastFileStorageClient;
        this.fastDfsProperties = fastDfsProperties;
    }

    /**
     * FastDFS图片文件上传
     * @param file 文件
     * @return 地址
     */
    public String uploadImageFile(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        // 检验文件的类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            throw new IllegalArgumentException("文件类型不合法");
        }

        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (Objects.isNull(bufferedImage)){
                throw new IllegalArgumentException("文件类型不合法");
            }

            // 保存到服务器，会默认上传到application.yml配置的ip的服务器
            String extension = FileUtils.getExtension(originalFilename);
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 生成url地址，返回
            return fastDfsProperties.getUrl() + storePath.getFullPath();

        } catch (Exception e) {
            log.error("上传图片到FastDFS失败", e);
            throw new Exception("上传图片到FastDFS失败");
        }
    }

}
